<template>
	<view>
		<uni-segmented-control :current="current" :values="depNameList" styleType="button" @clickItem="selectItem" />
		<view class="content">
			<view v-show="current === 0">
				<view v-for="option in options">{{ option.name }}</view>
			</view>
			<view v-show="current === 1">
				<view v-for="option in options">{{ option.name }}</view>
			</view>
		</view>
	</view>
</template>
<script lang="ts" setup>
	import { computed, onMounted, ref, shallowRef } from 'vue';

	const db = uniCloud.databaseForJQL()
	const tree = db.collection('codingguli-dep')
	const items = ref([])
	const options = ref([])
	const current = shallowRef(0)

	const queryItems = async () => {
		const { data } = await tree.get()
		items.value = data.filter(item => !item.parent_id)
	}

	const queryOptions = async () => {
		const { data } = await tree.where({
			parent_id: items.value[current.value]._id
		}).get()
		options.value = data
	}

	const selectItem = async (e) => {
		if (current.value != e.currentIndex) {
			current.value = e.currentIndex;
			queryOptions()
		}
	}

	const depNameList = computed(() => {
		return items.value.map(item => item.name)
	})

	onMounted(async () => {
		await  queryItems()
		queryOptions()
	})
</script>